const Router = require('koa-router');
const router = new Router();
const {db, QueryTypes} = require("../../models/db");
const {xe} = require("../../tools/tool");
const tool = require("../../tools/tool");
const {col, or} = require("@sequelize/core");
const xlsx = require("xlsx");
const path = require('path');

let billSets = {
    "ocr_api_url": "https://api.textin.com/ai/service/v2/recognize/table/multipage",
    "ocr_api_id": "a2249528c0439f39fc5de8479f215c0c",
    "ocr_api_code": "5bf919b0a90aaeb24d2557fc724c3e37",
    "web_local": "http://localhost:5050",
    "web_remote": "https://ps.sanzhiyun.cn",
    "api_local": "http://localhost:996/",
    "api_remote": "https://v5api.sanzhiyun.cn/",
    "tb_cols_len": 9,
    "buName_pre":"客户:",
    "buName_end":"电话:",
    "billDate_pre": "日期:",
    "billDate_len": 10,
    "bill_pre": "票号:",
    "bill_len": 13,
    "address_pre": "地址:",
    "address_end": "",
    "phone_start": "电话:",
    "phone_end": "地址:",
    "play": true,
    "bill_area": 240000,
    "img_ratio": 900,
    "invName": '商品名称'
}

const goodColSets = {
    price: '单价',
    invName: '商品名称',
    spec: '规格',
    unit: '单位',
    remark: '备注',
    qty: '数量',
    totalAmount: '',
    amount: '金额',
    disAmount: '返利'
}

const summarizeItems = (items) => {
    return items.reduce((acc, currentItem) => {
        // 创建一个唯一的键来标识invName和unit的组合
        const key = `${currentItem.invName}-${currentItem.spec}-${currentItem.unit}`;
        // 如果这个键在累加器中不存在，则创建一个新的对象
        if (!acc[key]) {
            acc[key] = { ...currentItem, qty: 0 };
        }
        // 累加qty
        acc[key].qty += tool.xe.toNumber(currentItem.qty);

        return acc;
    }, {})
}
const getSpec  = (spec) => {
    let sp = spec.split('*')
    if (sp.length === 2) {
        return sp[1]
    }
    return sp[1]
}
const removeDuplicatesRecursive = (arr, result = [], index = 0) => {
    // 如果数组遍历完毕，返回结果
    if (index >= arr.length) {
        return result;
    }

    let currentObj = arr[index];
    // 检查当前对象是否在结果中已经存在，考虑了嵌套的对象
    let isDuplicate = result.some(existingObj => deepEqual(existingObj, currentObj));

    // 如果当前对象不是重复的，则添加到结果中
    if (!isDuplicate) {
        result.push(currentObj);
    }

    // 递归调用，检查下一个对象
    return removeDuplicatesRecursive(arr, result, index + 1);
}
// 深度比较两个对象是否相等的函数
const deepEqual = (obj1, obj2) => {
    if (obj1 === obj2) return true;

    if (isPrimitive(obj1) || isPrimitive(obj2)) return obj1 === obj2;

    if (Object.keys(obj1).length !== Object.keys(obj2).length) return false;

    for (let key in obj1) {
        if (!obj2.hasOwnProperty(key)) return false;
        if (!deepEqual(obj1[key], obj2[key])) return false;
    }
    return true;
}
// 检查是否是基本类型或null
const isPrimitive = (val) => {
    return val == null || typeof val !== 'object';
}
router.post('/justdeliver/getGoodList', async ctx => {
    let tenantId = ctx.user.tenantId
    let goodsList = await db.query(`select id,invName,spec,unit1,unit2 from ps_goods where tenantId=${tenantId} `, {type: QueryTypes.SELECT})
    return ctx.suc('', goodsList)
})
router.post('/justdeliver/test', async ctx => {
    let tenantId = ctx.user.tenantId
    let bill = ctx.request.body.formData
    let model = await db.query(`select * from ps_sets where tenantId='${tenantId}'`, {type: QueryTypes.SELECT, plain: true})
    let sets = JSON.parse(model.sets)
    let uuid = ctx.request.body.uuid
    let billHead = await combHeadInfo(sets, bill)
    let ret = await combGoodInfo(sets, bill, billHead, tenantId)
    if(ret.stat) {
        let billNo = tool.xe.trim(ret.list[0].billNo)
        if (billNo) {
            let has = await db.models['psCargoInfo'].count({
                where: {
                    tenantId,
                    billNo,
                }
            })
            if (has > 0) {
                return ctx.err(billNo + ' 已配送过')
            }
        }
        for (let i = 0; i < ret.list.length; i++) {
            ret.list[i].uuid = uuid
            ret.list[i].tenantId = tenantId
            let hasOne = await db.models['psCargoTemp'].findOne({
                where: {
                    uuid,
                    tenantId,
                    billNo: ret.list[i].billNo,
                    invName: ret.list[i].invName,
                    spec: ret.list[i].spec,
                    qty: ret.list[i].qty,
                    price: ret.list[i].price,
                }
            })
            if(!hasOne) {
                await db.models['psCargoTemp'].create(ret.list[i])
            }
        }
        let list = await db.query(`select * from ps_cargo_temp where tenantId=${tenantId} and uuid='${uuid}'`,
            {type: QueryTypes.SELECT})
        let gp = await grpData(tenantId, list)
        return  ctx.suc('', {orders: gp.orders, grpData: gp.gpGoods})
    }
    else {
        return ctx.err(ret.msg)
    }
})
const isValidChar = (char) => {
    // 正则表达式：匹配英文字母（大小写）、数字及下划线
    const regex = /^[a-zA-Z0-9-]$/;
    return regex.test(char);
}
const combHeadInfo = async (sets, bill) => {
    // headInfo是数组
    let billInfos = sets.billInfos
    let headInfo = bill.headInfo
    for (let i = 0; i < billInfos.length; i++) {
        if(headInfo.indexOf(billInfos[i].billTitle) !== -1) {
            let headSets = billInfos[i].headSets
            let bill = {
                billNo: '',
                billDate: '',
                buName: '',
                address: ''
            }
            if(headSets.billNo) {
                let lineStr = ''
                for (let j = 0; j < headInfo.length; j++) {
                    let row = headInfo[j]
                    if(row.indexOf(headSets['billNo']) !== -1) {
                        let bill_index = row.indexOf(headSets['billNo']) + headSets['billNo'].length
                        let temp = row.substring(bill_index)
                        let bno = ''
                        for (let j = 0; j < temp.length; j++) {
                            if(isValidChar(temp[j])) {
                                bno += temp[j]
                            }
                            else {
                                break
                            }
                        }
                        bill.billNo = bno
                    }
                    if(headSets.billDate) {
                        let billDate_index = row.indexOf(headSets['billDate'])
                        let billDateLen = tool.xe.toNumber(headSets['billDateLen'])
                        if (billDate_index !== -1) {
                            bill.billDate = row.substring(billDate_index + headSets['billDate'].length, billDate_index + headSets['billDate'].length + billDateLen)
                        }
                    }
                    lineStr += row
                }
                //
                let buname_start = lineStr.indexOf(headSets['buName'])
                let buname_end = headSets['buNameNext']===''?'':lineStr.indexOf(headSets['buNameNext'])
                if (buname_start !== -1) {
                    if(buname_end) {
                        bill.buName = lineStr.substring(buname_start + headSets['buName'].length, lineStr.indexOf(headSets['buNameNext']))
                    }
                    else {
                        bill.buName = lineStr.substring(buname_start + headSets['buName'].length)
                    }
                }
                //
                let address_start = headSets['address'] ? lineStr.indexOf(headSets['address']): -1
                let address_end = headSets['addressNext']
                if (address_start !== -1 ) {
                    if(address_end) {
                        bill.address = lineStr.substring(address_start + headSets['address'].length, lineStr.indexOf(headSets['addressNext']))
                    }
                    else {
                        bill.address = lineStr.substring(address_start + headSets['address'].length )
                    }
                }
            }

            return bill
        }
    }
}
const combGoodInfo = async (sets, bill, billHead, tenantId) => {
    let billInfos = sets.billInfos
    let infos = bill.infos
    let headInfo = bill.headInfo
    for (let i = 0; i < billInfos.length; i++) {
        if(headInfo.indexOf(billInfos[i].billTitle) !== -1) {
            let goodTbInfo = billInfos[i].goodSets
            let billnos = []
            for (let j = 0; j < infos.length; j++) {
                let obj = {
                    billNo: billHead.billNo,
                    buName: billHead.buName.replace('\n', ''),
                    billDate: billHead.billDate,
                    address: billHead.address.replace('\n', ''),
                    invName: infos[j][goodTbInfo.invName].replace('\n', ''),
                    spec: infos[j][goodTbInfo.spec],
                    unit: infos[j][goodTbInfo.unit],
                    qty: infos[j][goodTbInfo.qty],
                    price: infos[j][goodTbInfo.price],
                    disAmount: goodTbInfo.disAmount ?(infos[j][goodTbInfo.disAmount]?infos[j][goodTbInfo.disAmount]:'') :'',
                    amount: infos[j][goodTbInfo.amount],
                    remark: infos[j][goodTbInfo.remark].replace('\n', ''),
                }
                if(isNaN(Number(obj.price))) {
                    if(obj.price.indexOf('/') !== -1) {
                        let arr = obj.price.split('/')
                        obj.price = tool.xe.toNumber(tool.xe.trim(arr[0]))
                    }
                }
                obj.specInt = 0
                if(isNaN(Number(obj.qty))) {
                    if(obj.qty.length > 1) {
                        obj.qty = tool.xe.toNumber(obj.qty.substring(0, obj.qty.length-1))
                        if(!obj.unit)
                            obj.unit =  tool.xe.trim(obj.qty.substring(obj.qty.length-1))
                    }
                }
                else {
                    obj.qty = tool.xe.toNumber(obj.qty)
                }
                let model = await db.models['psGoods'].findOne({
                    where: {
                        tenantId,invName: obj.invName,spec: obj.spec?obj.spec:''
                    }
                })
                obj.calNum = 0
                obj.unit1 = ''
                obj.unit2 = ''
                if(model) {
                    if(!obj.spec) {
                        obj.spec = model.spec
                    }
                    if(model.spec.indexOf('*') !== -1) {
                        let arr = model.spec.split('*')
                        obj.specInt = tool.xe.toNumber(tool.xe.trim(arr[1]))
                    }
                    else {
                        obj.specInt = tool.xe.toNumber(model.spec)
                    }
                    obj.calNum = obj.unit === model.unit1?obj.specInt:1
                    obj.unit1 = model.unit1?model.unit1:''
                    obj.unit2 = model.unit2?model.unit2:''
                }
                obj.qty = tool.xe.toNumber(obj.qty)
                obj.price = tool.xe.toNumber(obj.price)
                obj.disAmount = tool.xe.toNumber(obj.disAmount)
                obj.amount = tool.xe.toNumber(obj.amount)
                if(tool.minus(tool.multiply(obj.qty,obj.price),obj.disAmount) !== tool.xe.toNumber(obj.amount)) {
                    return {stat: false, msg: "合计失败---"+obj.invName}
                }
                billnos.push(obj)
            }
            return {stat: true, list: billnos}
        }
    }
    return {stat: false, msg: '无返回数据'}
}
const grpData = async (tenantId, orders) => {
    let gpbuName = tool.xe.groupBy(orders, 'buName')
    let gpos = []
    for(let i in gpbuName) {
        gpos.push({
            buName: gpbuName[i][0].buName,
            billNo: gpbuName[i][0].billNo,
            billDate: gpbuName[i][0].billDate,
            address: gpbuName[i][0].address,
            uuid: gpbuName[i][0].uuid,
        })
    }
    let grp = []

    if(orders.length > 0) {
        let summarized = summarizeItems(orders)
        grp =  Object.values(summarized);
    }
    for (let i = 0; i < grp.length; i++) {
        if(tool.xe.toNumber(grp[i].calNum) > 0) {
            if(grp[i].unit1 && grp[i].unit2) {
                let gps = tool.xe.multiply(grp[i].qty,grp[i].calNum)/grp[i].specInt
                let zhengjian = Math.floor(gps)

                let lingp = tool.xe.subtract(gps, zhengjian)
                let ping = tool.xe.toFixed(tool.xe.multiply(lingp, grp[i].specInt), 0)
                grp[i].assQty = ''
                if(tool.xe.toNumber(zhengjian) !== 0) {
                    grp[i].assQty = zhengjian + grp[i].unit1
                }
                if(tool.xe.toNumber(ping) !== 0) {
                    grp[i].assQty = grp[i].assQty + (ping + grp[i].unit2)
                }
                grp[i].unit = grp[i].unit1
                grp[i].qty = tool.xe.round(gps, 6)
            }
            else {
                grp[i].assQty = grp[i].qty + grp[i].unit
            }
        }
        else {
            grp[i].assQty =  grp[i].qty + grp[i].unit
        }
    }

    return {orders: gpos, gpGoods: grp}
}
// 检测是否已配送过
router.post('/justdeliver/gpList', async ctx => {
    let tenantId = ctx.user.tenantId
    let bill = ctx.request.body.formData
    
    let model = await db.query(`select * from ps_sets where tenantId='${tenantId}'`, {type: QueryTypes.SELECT, plain: true})
    let sets = JSON.parse(model.sets)
    let uuid = ctx.request.body.uuid
    let billHead = await combHeadInfo(sets, bill)
    let ret = await combGoodInfo(sets, bill, billHead, tenantId)
    if(ret.stat) {
        let billNo = tool.xe.trim(ret.list[0].billNo)
        if (billNo) {
            let has = await db.models['psCargoInfo'].count({
                where: {
                    tenantId,
                    billNo,
                }
            })
            if (has > 0) {
                return ctx.err(billNo + ' 已配送过')
            }
        }
        for (let i = 0; i < ret.list.length; i++) {
            ret.list[i].uuid = uuid
            ret.list[i].tenantId = tenantId
            let hasOne = await db.models['psCargoTemp'].findOne({
                where: {
                    uuid,
                    tenantId,
                    billNo: ret.list[i].billNo,
                    invName: ret.list[i].invName,
                    spec: ret.list[i].spec,
                    qty: ret.list[i].qty,
                    price: ret.list[i].price,
                }
            })
            if(!hasOne) {
                await db.models['psCargoTemp'].create(ret.list[i])
            }
        }
        let list = await db.query(`select * from ps_cargo_temp where tenantId=${tenantId} and uuid='${uuid}'`,
            {type: QueryTypes.SELECT})
        let gp = await grpData(tenantId, list)
        return  ctx.suc('', {orders: gp.orders, grpData: gp.gpGoods})
    }
    else {
        return ctx.err(ret.msg)
    }

})

router.post('/justdeliver/getPrint', async ctx => {
    try {
        let cargoId = ctx.request.body.cargoId
        let sendPrintName = ctx.request.body.sendPrintName
        let printDetail = [];
        let tenantId = ctx.user.tenantId;
        let print = [];
        let cargo = await db.models['psCargo'].findOne({
            where: {
                id: cargoId
            }
        })
        let cargoInfo = await db.query(`select * from ps_cargo_info where tenantId=${tenantId} and iid=${cargoId} `,{type: QueryTypes.SELECT})
        let sqlgoods = `select a.* from ps_cargo_info_goods a  where a.tenantId=${tenantId} 
                                         and a.iid=${cargoId} order by invName `
        let cargoInfoGoods = await db.query(sqlgoods,{type: QueryTypes.SELECT})
        let billNos = []
        let zds = [];
        cargoInfo.map(row => {
            if(billNos.indexOf(row.billNo) === -1) {
                billNos.push(row.billNo)
            }
            if(zds.indexOf(row.buName) === -1) {
                zds.push(row.buName)
            }
        })
        let gpGoods = [] // grpgoods(cargoInfoGoods)

        let grp = []

        if(cargoInfoGoods.length > 0) {
            let summarized = summarizeItems(cargoInfoGoods)
            grp =  Object.values(summarized);
        }
        for (let i = 0; i < grp.length; i++) {
            if(tool.xe.toNumber(grp[i].calNum) > 0) {
                if(grp[i].unit1 && grp[i].unit2) {
                    let gps = tool.xe.multiply(grp[i].qty,grp[i].calNum)/grp[i].specInt
                    let zhengjian = Math.floor(gps)

                    let lingp = tool.xe.subtract(gps, zhengjian)
                    let ping = tool.xe.toFixed(tool.xe.multiply(lingp, grp[i].specInt), 0)
                    grp[i].assQty = ''
                    if(tool.xe.toNumber(zhengjian) !== 0) {
                        grp[i].assQty = zhengjian + grp[i].unit1
                    }
                    if(tool.xe.toNumber(ping) !== 0) {
                        grp[i].assQty = grp[i].assQty + (ping + grp[i].unit2)
                    }
                }
                else {
                    grp[i].assQty =  grp[i].qty + grp[i].unit
                }
            }
            else {
                grp[i].assQty =  grp[i].qty + grp[i].unit
            }
            gpGoods.push(grp[i])
        }


        let sumCount = 0
        for (let i = 0; i < gpGoods.length; i++) {
            sumCount += tool.xe.toNumber(gpGoods[i].qty)
        }
        sumCount = tool.xe.toNumber(sumCount)
        let tbhtml = '<table style="border-collapse:collapse;width:270px;"><tbody>'
        //
        tbhtml += `<tr><td colspan='2' style='padding: 5px 0;text-align: center;font-weight: bolder;font-size: 16px;width:270px;'>配送单(${cargo.deliverNames})</td></tr>`
        tbhtml += `<tr><td colspan='2' style='padding: 5px 0;text-align: left;font-size: 13px;width:270px;font-weight: bolder;'>配送号：${cargo.billNo}</td></tr>`
        tbhtml += `<tr><td colspan='2' style='padding: 5px 0;text-align: left;font-size: 13px;width:270px;font-weight: bolder;'>日期：${cargo.billDate}</td></tr>`
        tbhtml += `<tr><td colspan='2' style='padding: 5px 0;text-align: left;font-size: 13px;width:270px;font-weight: bolder;'>送货员：${cargo.deliverNames}</td></tr>`
        tbhtml += `<tr><td style='padding: 5px 0;text-align: left;font-weight: bolder;font-size: 14px; '>终端数：${zds.length}</td><td style='padding: 5px 0;text-align: left;font-weight: bolder;font-size: 14px; '>票据数：${billNos.length}</td></tr>`
        tbhtml += `<tr><td colspan='2' style='padding: 5px 0;text-align: left;font-size: 12px;width:270px;font-weight: bolder;'>票号：${billNos.join(', ')}</td></tr>`
        tbhtml += "<tr><td colspan='2' style='padding: 5px 0;text-align: center;font-weight: bolder;font-size: 14px;width:270px;border-bottom: 1px solid black;margin-bottom: 5px;'>商品汇总</td></tr>"

        for (let i = 0; i < gpGoods.length; i++) {
            let row = gpGoods[i]
            tbhtml += `<tr><td style="padding: 2px 0;width: 200px;text-align: left;font-weight: bolder;">${row.invName}${row.spec}</td><td style="width: 70px;text-align: right;">${row.assQty}</td></tr>`
        }
        tbhtml += "<tr><td style='border-bottom: 1px solid black;'></td><td style='border-bottom: 1px solid black'></td></tr>"
        tbhtml += '<tr><td style="padding: 2px 0;width: 200px;text-align: left;"></td><td style="width: 70px;text-align: right;padding-right: 17px;">'+sumCount+'</td></tr>'
        tbhtml += "<tr><td colspan='2' style='height: 80px;'></td> </tr>"
        tbhtml += '</tbody></table>'
        return ctx.suc('', {data: tbhtml, printView: false})
    }
    catch (e) {
        return ctx.err(e)
    }
})
router.post('/justdeliver/delCargoItem', async ctx => {
    let tenantId = ctx.user.tenantId
    let uuid = ctx.request.body.uuid
    let billNo = ctx.request.body.billNo
    await db.models['psCargoTemp'].destroy({
        where: {
            tenantId,uuid,billNo
        }
    })
    let list = await db.query(`select * from ps_cargo_temp where tenantId=${tenantId} and uuid='${uuid}'`,{type: QueryTypes.SELECT})
    let gp = await grpData(tenantId, list)
    return  ctx.suc('', {orders: gp.orders, grpData: gp.gpGoods})
})
router.post('/justdeliver/delDetailCargoItem', async ctx => {
    let uid = ctx.user.id;
    let cargoId = ctx.request.body.cargoId
    let cargoInfoId = ctx.request.body.iid
    let tenantId = ctx.user.tenantId;

    await db.transaction(async () => {
        let model = await db.models['psCargoInfo'].findOne({
            where: {
                id: cargoInfoId
            }
        })
        let billNo = model.billNo
        await db.models['psCargoInfo'].destroy({
            where: {
                id: cargoInfoId
            }
        })
        await db.models['psCargoInfoGoods'].destroy({
            where: {
                billNo,
                iid: cargoId
            }
        })
        let hasOne =  await db.models['psCargoInfo'].count({
            where: {
                iid: cargoId
            }
        })
        if(hasOne === 0) {
            await db.models['psCargo'].destroy({
                where: {
                    id: model.iid
                }
            })
        }
        let obj = {
            tenantId,
            iid: cargoId,
            msg: JSON.stringify(model),
            msgType: '删除',
            ct: tool.getTime()
        }
        await db.models['psLog'].create(obj)
    })
    return ctx.suc('已删除')

})

router.post('/justdeliver/gpRkList', async ctx => {
    let tenantId = ctx.user.tenantId
    let bill = ctx.request.body.formData
    let model = await db.query(`select * from ps_sets where tenantId='${tenantId}'`, {type: QueryTypes.SELECT, plain: true})
    let sets = JSON.parse(model.sets)
    let uuid = ctx.request.body.uuid
    let billHead = await combHeadInfo(sets, bill)
    let ret = await combGoodInfo(sets, bill, billHead, tenantId)
    if(ret.stat) {
        let billNo = tool.xe.trim(ret.list[0].billNo)
        if (billNo) {
            let has = await db.models['psCargoInfo'].count({
                where: {
                    tenantId,
                    billNo,
                }
            })
            if (has > 0) {
                return ctx.err(billNo + ' 已配送过')
            }
        }
        for (let i = 0; i < ret.list.length; i++) {
            ret.list[i].uuid = uuid
            ret.list[i].tenantId = tenantId
            let hasOne = await db.models['psCargoTemp'].findOne({
                where: {
                    uuid,
                    tenantId,
                    billNo: ret.list[i].billNo,
                    invName: ret.list[i].invName,
                    spec: ret.list[i].spec,
                    qty: ret.list[i].qty,
                    price: ret.list[i].price,
                }
            })
            if(!hasOne) {
                await db.models['psCargoTemp'].create(ret.list[i])
            }
        }
        let list = await db.query(`select * from ps_cargo_temp where tenantId=${tenantId} and uuid='${uuid}'`,
            {type: QueryTypes.SELECT})
        list.map(row => {
            row.price = row.price?row.price:''
            row.qty = row.price?row.qty:''
            row.amount = row.amount?row.amount:''
        })
        return  ctx.suc('', {orders: list})
    }
    else {
        return ctx.err(ret.msg)
    }
})
// 保存入库
router.post('/justdeliver/saveRk', async ctx => {
    let tenantId = ctx.user.tenantId
    let uuid = ctx.request.body.uuid
    let orders = await db.query(`select * from ps_cargo_temp where uuid='${uuid}' `,{type: QueryTypes.SELECT})
    // let psCkId = ctx.request.body.psCkId
    // if(!psCkId) return ctx.err('没有选择仓库')
    if(orders.length === 0) return ctx.err('没有上传数据')
    for (let i = 0; i < orders.length; i++) {
        let billNo = orders[i].billNo
        let invName = orders[i].invName
        let numSql = `select count(*) total from ps_rk where tenantId=${tenantId} and 
                          billNo='${billNo}' and invName='${invName}' `
        let num = await db.query(numSql, {type: QueryTypes.SELECT, plain: true})
        if(num.total > 0) {
            return ctx.err(billNo +' 已存在')
        }
    }
    let rks = []
    for (let i = 0; i < orders.length; i++) {
        delete orders[i]._RID
        orders[i].ctime = tool.getTime()
        orders[i].tenantId = tenantId
        // orders[i].psCkId = psCkId
    }
    await db.models['psRk'].bulkCreate(orders)
    return ctx.suc('保存成功')
})
router.post('/justdeliver/getCkList', async ctx => {
    let tenantId = ctx.user.tenantId
    let list = await db.query(`select id label,name text from ps_ck where tenantId=${tenantId}`, {
        type: QueryTypes.SELECT
    })
    return ctx.suc('', list)
})
router.post('/justdeliver/saveCk', async ctx => {
    let tenantId = ctx.user.tenantId
    let ckList = ctx.request.body.ckList
    if(ckList.length > 0) {
        await db.transaction(async () => {
            for (let i = 0; i < ckList.length; i++) {
                if(ckList[i].label) {
                    await db.models['psCk'].update({name: ckList[i].text},{
                        where: {
                            tenantId,
                            id: ckList[i].label
                        }
                    })
                }
                else {
                    await db.models['psCk'].create({tenantId, name: ckList[i].text})
                }
            }
        })
    }
    return ctx.suc('保存成功')
})
router.post('/justdeliver/delCk', async ctx => {
    let tenantId = ctx.user.tenantId
    let id = ctx.request.body.id
    let has = await db.models['psRk'].count({
        where: {
            psCkId: id
        }
    })
    if(has > 0) return ctx.err('已使用，不能删除')
    await db.models['psCk'].destroy({
        where: {
            id
        }
    })
    return ctx.suc('')
})
router.post('/justdeliver/getRkList', async ctx => {
    let tenantId = ctx.user.tenantId
    let id = ctx.request.body.id
    let formData = ctx.request.body.formData
    let sql = `select a.*,b.name ckName from ps_rk a left join ps_ck b on a.psCkId=b.id where a.tenantId=${tenantId} and a.billDate<>'1970-01-01' `
    if(formData.beginDate) {
        sql = sql + ` and a.billDate>='${formData.beginDate}' `
    }
    if(formData.endDate) {
        sql = sql + ` and a.billDate<='${formData.endDate}' `
    }
    if(formData.billNo) {
        sql = sql + ` and a.billNo like '%${tool.xe.trim(formData.billNo)}%' `
    }
    if(formData.invName) {
        sql = sql + ` and a.invName like '%${tool.xe.trim(formData.invName)}%' `
    }
    if(formData.buName) {
        sql = sql + ` and a.buName like '%${tool.xe.trim(formData.buName)}%' `
    }
    let has = await db.query(sql,{type: QueryTypes.SELECT})
    return ctx.suc('', has)
})
router.post('/justdeliver/delRkItem', async ctx => {
    let tenantId = ctx.user.tenantId
    let id = ctx.request.body.id
    await db.models['psRk'].destroy({
        where: {
            id, tenantId
        }
    })
    return ctx.suc('')
})
router.post('/justdeliver/getStockList', async ctx => {
    let tenantId = ctx.user.tenantId
    let id = ctx.request.body.id
    let formData = ctx.request.body.formData
    let beginDate = formData.beginDate
    let endDate = formData.endDate
    let sql = `
    WITH orders as   (
        SELECT billDate,invName,isnull(spec,'') spec,price,isnull(priceUnit,'') priceUnit,qty,isnull(qtyUnit,'') qtyUnit,amount,isnull(unit1,'') unit1,isnull(unit2 ,'') unit2 ,isnull(specArc,'') specArc,isnull(calNum,0) calNum, 'in' type from ps_rk 
        WHERE tenantId=${tenantId} and billDate <= '${endDate}'
        union all 
        SELECT a.billDate,b.invName,isnull(spec,'') spec,price,isnull(priceUnit,'') priceUnit,qty,isnull(qtyUnit,'') qtyUnit,amount,isnull(unit1,'') unit1,isnull(unit2 ,'') unit2,isnull(specArc,'') specArc,isnull(calNum,0) calNum, 'out' type from ps_cargo  a inner join ps_cargo_info_goods b on a.id=b.iid and a.billDate <= '${endDate}' and a.tenantId=${tenantId} 
        )  
        select invName,spec,iif(type='in',qty,-qty) initQty,qtyUnit,0 inQty,0 outQty ,1 isInit from orders WHERE billDate<'${beginDate}' 
        union all 
        select invName,spec,0 initQty,qtyUnit,case when type='in' then qty else 0 end inQty,case when type='out' then qty else 0 end outQty, 0 isInit from orders WHERE billDate BETWEEN '${beginDate}' and '${endDate}' 
            
    `
    let list = await db.query(sql, {type: QueryTypes.SELECT})
    for (let i = 0; i < list.length; i++) {
        list[i].leftQty = tool.xe.toNumber(list[i].initQty) + tool.xe.toNumber(list[i].inQty) - tool.xe.toNumber(list[i].outQty)
    }
    for (let i = 0; i < list.length; i++) {
        list[i].leftQty = list[i].leftQty?list[i].leftQty:''
        list[i].initQty = list[i].initQty?list[i].initQty:''
        list[i].inQty = list[i].inQty?list[i].inQty:''
        list[i].outQty = list[i].outQty?list[i].outQty:''
        list[i].beginDate = formData.beginDate
        list[i].endDate = formData.endDate
    }

    return ctx.suc('', list)
})
router.post('/justdeliver/importQc', async ctx => {
    let tenantId = ctx.user.tenantId
    let url = ctx.request.body.url
    const workbook = xlsx.readFile('./uploads/'+url);
    // 获取第一个工作表的名字
    const sheetName = workbook.SheetNames[0];
    // 获取工作表
    const worksheet = workbook.Sheets[sheetName];
    // 将工作表转换为JSON
    const jsonData = xlsx.utils.sheet_to_json(worksheet);
    for (let i = 0; i < jsonData.length; i++) {
        jsonData[i]['商品名称'] = tool.xe.trim(jsonData[i]['商品名称'])
        jsonData[i]['规格'] = tool.xe.toString(jsonData[i]['规格'])
        jsonData[i]['单位'] = tool.xe.trim(jsonData[i]['单位'])
        jsonData[i]['数量'] = tool.xe.trim(jsonData[i]['数量'])
    }
    if(jsonData.length > 0) {
        await db.transaction(async () => {
            let pageSize = 900
            let pages = Math.ceil(jsonData.length/pageSize)
            await db.models['psRk'].destroy({
                where: {
                    tenantId,
                    billDate: '1970-01-01'
                }
            })
            for (let i = 0; i < pages; i++) {
                let skip = i * pageSize
                let sqlarr = []
                let rets = jsonData.slice(skip, pageSize)
                for (let j = 0; j < rets.length; j++) {
                    let invName = rets[j]['商品名称']
                    let spec = rets[j]['规格']
                    let qty = rets[j]['数量']
                    let unit = rets[j]['单位']
                    if(!invName) return ctx.err('没有商品名称')
                    if(!spec) return ctx.err('没有规格')
                    if(!unit) return ctx.err('没有单位')
                    if(!qty) return ctx.err('没有数量')
                    if(spec.indexOf('*') === -1) return ctx.err('规格格式为 x*x')
                    let specInt = 1
                    let specArr = spec.split('*')
                    if(specArr.length === 2) specInt = specArr[1]
                    sqlarr.push({
                        tenantId,
                        billNo: '',
                        billDate: '1970-01-01',
                        buName: '',
                        invName,
                        spec,
                        price: 0,
                        qty,
                        amount: 0,
                        specInt,
                        priceUnit: '',
                        unit,
                        qtyUnit: 'unit'

                    })
                }

                await db.models['psRk'].bulkCreate(sqlarr)
            }
        })
        return ctx.suc('导入成功')
    }
})


router.post('/justdeliver/userReg', async ctx => {
    let username = tool.xe.trim(ctx.request.body.username)
    let userpwd = tool.xe.trim(ctx.request.body.userpwd)
    let mobile = tool.xe.trim(ctx.request.body.mobile)
    let company = tool.xe.trim(ctx.request.body.company)
    let tenant = await db.models['tenant'].count({
        where: {
            name: company
        }
    })
    if(tenant > 0) return ctx.err('存在相同的公司名称，请换一个')
    let admin = await db.models['admin'].count({
        where: {
            username
        }
    })
    if(admin > 0) return ctx.err('已存在相同的用户名,请换一个')
    await db.transaction(async () => {
        let tenModel = db.models['tenant'].build()
        tenModel.name = company
        tenModel.stat = 1
        tenModel.state = '正常'
        tenModel.mobile = mobile
        tenModel.ct = tool.getTime()
        await tenModel.save()
        if(tenModel.id) {
            let role = await db.models['role'].create({
                tenantId: tenModel.id,
                name: '管理员',
                isInit: 1,
                isDel: 0,
                pinYin: tool.py('管理员'),
                title: '管理员'
            })
            let user = await db.models['admin'].create({
                tenantId: tenModel.id,
                userpwd: tool.crypto.MD5(userpwd),
                token: tool.uuid(),
                username: username,
                name: username,
                mobile,
                roleId: role.id,
                roleName: role.name,
                pinYin: tool.py(username),
                ctime: tool.getTime()
            })
            if(!user.id) {
                throw new SQLException()
            }
        }
    })
    return ctx.suc('注册成功')
})
// 手机版本汇总数据
router.post('/justdeliver/gpBills', async ctx => {
    let sql = ctx.request.body.sqls
    let data = await db.query(sql, {type: QueryTypes.SELECT})
    return ctx.suc('', data)
})

router.post('/justdeliver/shy', async ctx => {
    let tenantId = ctx.user.tenantId;
    let which = ctx.request.body.which
    if (which === 'list') {
        let list = await db.query(`select * from ps_shy where tenantId=${tenantId} order by id asc`,{type: QueryTypes.SELECT})
        return ctx.suc('', list)
    }
    if (which === 'save') {
        let name = ctx.request.body.name
        let has = `select count(*) total from ps_shy where tenantId=${tenantId} and name='${name}' `
        let model = await db.query(has, {type: QueryTypes.SELECT, plain: true})
        if (model && model.total == 0) {
            let insert = `insert into ps_shy(tenantId,name) values (${tenantId}, '${name}') `
            await db.query(insert, {type: QueryTypes.INSERT})
            return ctx.suc('保存成功')
        }
        else {
            return ctx.err('已存在相同名称 '+name)
        }
    }
    if (which === 'del') {
        let name = ctx.request.body.name
        await db.query(`delete from ps_shy where tenantId=${tenantId} and name='${name}' `,{type: QueryTypes.DELETE})
        return ctx.suc('删除成功')
    }

    return  ctx.err('')
})
router.post('/justdeliver/goods', async ctx => {
    let tenantId = ctx.user.tenantId;
    let which = ctx.request.body.which
    if (which === 'list') {
        let list = await db.query(`select * from ps_goods where tenantId=${tenantId} order by id asc`,{type: QueryTypes.SELECT})
        return ctx.suc('', list)
    }
    if (which === 'save') {
        let formData = ctx.request.body.formData
        if(!formData.unit1) return ctx.err('没有大单位')
        if(!formData.unit2) return ctx.err('没有小单位')
        if(!formData.invName) return ctx.err('没有商品')
        if(!formData.spec) return ctx.err('没有规格')
        if(formData.unit1.length !== 1) return ctx.err('大单位只能有1个字')
        if(formData.unit2.length !== 1) return ctx.err('小单位只能有1个字')
        if(formData.spec.indexOf('*') === -1) return ctx.err('规格就高 1*x')
        if(formData.id) {
            let model = await db.models['psGoods'].findOne({
                where: {
                    tenantId,id: formData.id
                }
            })
            model.invName = formData.invName
            model.spec = formData.spec
            model.unit1 = formData.unit1
            model.unit2 = formData.unit2
            await model.save()
        }
        else {
            let model = db.models['psGoods'].build()
            model.tenantId = tenantId
            model.invName = formData.invName
            model.spec = formData.spec
            model.unit1 = formData.unit1
            model.unit2 = formData.unit2
            await model.save()
        }
        return ctx.suc('保存成功')
    }
    if (which === 'del') {
        let id = ctx.request.body.id
        await db.query(`delete from ps_goods where tenantId=${tenantId} and id='${id}' `,{type: QueryTypes.DELETE})
        return ctx.suc('删除成功')
    }
    if(which === 'exportIn') {
        let formData = ctx.request.body.formData
        const workbook = xlsx.readFile('./uploads/'+formData);
        // 获取第一个工作表的名字
        const sheetName = workbook.SheetNames[0];
        // 获取工作表
        const worksheet = workbook.Sheets[sheetName];
        // 将工作表转换为JSON
        const jsonData = xlsx.utils.sheet_to_json(worksheet);
        for (let i = 0; i < jsonData.length; i++) {
            jsonData[i]['商品名称'] = tool.xe.trim(jsonData[i]['商品名称'])
            jsonData[i]['规格'] = tool.xe.toString(jsonData[i]['规格'])
            jsonData[i]['大单位'] = tool.xe.trim(jsonData[i]['大单位'])
            jsonData[i]['小单位'] = tool.xe.trim(jsonData[i]['小单位'])
        }
        if(jsonData.length > 0) {
            let pageSize = 900
            let pages = Math.ceil(jsonData.length/pageSize)
            for (let i = 0; i < pages; i++) {
                let skip = i * pageSize
                let sqlarr = []
                let rets = jsonData.slice(skip, pageSize)
                for (let j = 0; j < rets.length; j++) {
                    let invName = rets[j]['商品名称']
                    let spec = rets[j]['规格']
                    let unit1 = rets[j]['大单位']
                    let unit2 = rets[j]['小单位']
                    if(!invName) return ctx.err('没有商品名称')
                    if(!spec) return ctx.err('没有规格')
                    if(!unit1) return ctx.err('没有大单位')
                    if(!unit2) return ctx.err('没有小单位')
                    if(unit1.length !== 1) return ctx.err('大单位只能有1个字')
                    if(unit2.length !== 1) return ctx.err('小单位只能有1个字')
                    if(spec.indexOf('*') === -1) return ctx.err('规格格式为 1*x')
                    sqlarr.push(` select ${tenantId} tenantId, '${invName}' invName,'${spec}' spec, '${unit1}' unit1,'${unit2}' unit2 `)
                }
                let sel = sqlarr.join(' union ')
                let sql = `merge into ps_goods a using (${sel}) b
                    on a.tenantId=b.tenantId and  a.invName=b.invName
                     when matched then update set a.spec=b.spec,a.unit1=b.unit1,a.unit2=b.unit2
                     when not matched then insert(tenantId,invName,spec,unit1,unit2) values(
                     b.tenantId,b.invName,b.spec,b.unit1,b.unit2);`
                await db.query(sql, {type: QueryTypes.UPDATE})
            }
            return ctx.suc('导入成功')
        }
    }

    return  ctx.err('')
})
router.post('/justdeliver/printname', async ctx => {
    let tenantId = ctx.user.tenantId;
    let which = ctx.request.body.which
    if(which === 'get') {
        let model = await db.models['psPrint'].findOne({
            where: {
                tenantId
            }
        })
        if(model) {
            return ctx.suc('', model.name)
        }
        return ctx.suc('', '')

    }
    if (which === 'save') {
        let name =  tool.xe.trim(ctx.request.body.sendPrintName)
        let model = await db.models['psPrint'].findOne({
            where: {
                tenantId
            }
        })
        if(model) {
            model.name = name
            await model.save()
        }
        else {
            model = db.models['psPrint'].build()
            model.tenantId = tenantId
            model.name = name
            await model.save()
        }
        return  ctx.suc('保存成功')
    }
})
// 装车
router.post('/justdeliver/toCargo', async ctx => {
    let tenantId = ctx.user.tenantId;
    let body = ctx.request.body
    let deliverNames = body.deliverNames
    let uuid = body.uuid

    let orders = await db.query(`select * from ps_cargo_temp where tenantId=${tenantId} and 
                                  uuid ='${uuid}'`, {type: QueryTypes.SELECT})
    if(orders.length === 0) return ctx.err('没有配送单据')
    let billDate = tool.getDay()
    let ctime = tool.getTime();
    if (!deliverNames) return ctx.err('请选择送货员');
    let billDateNo = tool.getDay('',0,'','YYYYMMDD')
    let cargo = {
        tenantId,
        billDate,
        deliverNames,
        stat: '待确认',
        ctime
    }
    let cgo = await db.models['psCargo'].findOne({
        where: {
            tenantId,
            billDate
        },
        order: [['id', 'desc']]
    })
    if(cgo){
        let bno = cgo.billNo.split('-')
        let c = tool.xe.toInteger(bno[1]) + 1;
        cargo.billNo = 'PS' + billDateNo + '-' + c;
    }
    else {
        cargo.billNo = 'PS' +billDateNo + '-1';
    }
    //

    let psId = await db.transaction(async () => {
        let iid = await db.models['psCargo'].create(cargo)

        let orderArr = []
        for (let i = 0; i < orders.length; i++) {
            let model = {}
            model.tenantId = iid.tenantId
            model.billNo = orders[i].billNo
            model.billDate = orders[i].billDate
            model.buName = orders[i].buName
            model.address = orders[i].address
            model.iid = iid.id
            orderArr.push(model)
        }
        await db.models['psCargoInfo'].bulkCreate(orderArr)
        let goods = []
        for (let i = 0; i < orders.length; i++) {
            let row = orders[i]
            let obj = {
                tenantId,
                iid: iid.id,
                invName: row.invName,
                spec: tool.xe.toString(row.spec),
                calNum: tool.xe.toString(row.calNum),
                qty: tool.xe.toString(row.qty),
                qtyUnit: row.qtyUnit,
                unit: row.unit,
                price: tool.xe.toString(row.price),
                priceUnit: row.priceUnit,
                totalAmount: tool.xe.toString(row.totalAmount),
                disAmount: tool.xe.toString(row.disAmount),
                amount: tool.xe.toString(row.amount),
                remark: row.remark?row.remark:'',
                unit1: row.unit1,
                unit2: row.unit2,
                specArc: tool.xe.toString(row.specArc),
                billNo: row.billNo,
                specInt: row.specInt,
            }
            goods.push(obj)
        }
        await db.models['psCargoInfoGoods'].bulkCreate(goods)
        await db.models['psCargoTemp'].destroy({
            where: {
                tenantId, uuid
            }
        })
        return iid.id
    })

    if(psId) {
        return ctx.suc('装车成功', psId);
    }
    else {
        return ctx.err('保存失败');
    }

})
// 待配送
router.post('/justdeliver/unDeliver', async ctx => {
    let uid = ctx.user.id;
    let name = ctx.user.name;
    let tenantId = ctx.user.tenantId;
    let sql = ` select deliverNames,count(*) nums from ps_cargo where tenantId=${tenantId} and stat='待确认' GROUP BY deliverNames `
    let list = await db.query(sql, {type: QueryTypes.SELECT})
    return ctx.suc('', list)

})
// 根据配送员查询详情
router.post('/justdeliver/getCargoDetail', async ctx => {
    let uid = ctx.user.id;
    let deliverNames = ctx.request.body.deliverNames;
    let tenantId = ctx.user.tenantId;
    let sql = ` select * from ps_cargo where tenantId=${tenantId} and deliverNames='${deliverNames}' and stat='待确认' `
    let cargo = await db.query(sql, {type: QueryTypes.SELECT})

    if (cargo.length > 0) {
        let iid = []
        cargo.map(row => {
            iid.push(row.id)
        })
        let infos = await db.query(`select distinct tenantId,billDate,buName,address,iid,billNo from ps_cargo_info where tenantId=${tenantId} and iid in(${iid.join(',')})`,
            {type: QueryTypes.SELECT})

        let infosGoods = await db.query(`select * from ps_cargo_info_goods 
         where tenantId=${tenantId} and iid in(${iid.join(',')}) order by invName `,{type: QueryTypes.SELECT})

        for (let i = 0; i < cargo.length; i++) {
            cargo[i].infos = []
            for (let j = 0; j < infos.length; j++) {
                if(cargo[i].id === infos[j].iid) {
                    cargo[i].infos.push(infos[j])
                }
            }
            cargo[i].goods =  []
            for (let j = 0; j < infosGoods.length; j++) {
                if(cargo[i].id === infosGoods[j].iid) {
                    cargo[i].goods.push(infosGoods[j])
                }
            }
        }
        return ctx.suc('', cargo)
    }
    return ctx.suc('', [])
})
// 整车删除
router.post('/justdeliver/delCargo', async ctx => {
    let cargoId = ctx.request.body.cargoId;
    let tenantId = ctx.user.tenantId;

    let cargo = await db.query(`select * from ps_cargo where tenantId=${tenantId} and id=${cargoId}`)
    let cargoInfo = await db.query(`select * from ps_cargo_info where tenantId=${tenantId} and iid=${cargoId}`)
    let cargoGoods = await db.query(`select * from ps_cargo_info_goods where tenantId=${tenantId} and iid=${cargoId}`)
    cargo.infos = cargoInfo
    cargo.goods = cargoGoods
    let obj = {
        tenantId,
        iid: cargoId,
        msg: JSON.stringify(cargo),
        msgType: '删除',
        ct: tool.getTime()
    }
    await db.transaction(async () => {
        await db.query(` delete from ps_cargo  where tenantId=${tenantId} and id=${cargoId} `, {type: QueryTypes.UPDATE})
        await db.query(` delete from ps_cargo_info  where tenantId=${tenantId} and iid=${cargoId} `, {type: QueryTypes.UPDATE})
        await db.query(` delete from ps_cargo_info_goods  where tenantId=${tenantId} and iid=${cargoId} `, {type: QueryTypes.UPDATE})
        await db.models['psLog'].create(obj)
    })

    return ctx.suc('已删除')
})

router.post('/justdeliver/confirmCargo', async ctx => {
    let cargoId = ctx.request.body.cargoId;
    let tenantId = ctx.user.tenantId;

    let sql = ` update ps_cargo set stat='已完成' where tenantId=${tenantId} and id=${cargoId} `
    await db.query(sql, {type: QueryTypes.UPDATE})

    return ctx.suc('已完成')

})
// 取打印数据


// 出货统计
router.post('/justdeliver/gpCargos', async ctx => {
    let beginDate = ctx.request.body.beginDate
    let endDate = ctx.request.body.endDate
    let deliverNames = ctx.request.body.deliverNames
    let billNo = ctx.request.body.billNo
    let excel = ctx.request.body.excel
    let tenantId = ctx.user.tenantId;
    let beg = beginDate
    let end = endDate

    let sql = `select a.id,
    a.billNo psBillNo,a.billDate psBillDate,a.deliverNames,a.stat from ps_cargo a  
         where a.tenantId=${tenantId} and a.billDate between '${beg}' and '${end}' `
    if(deliverNames) {
        sql += ` and a.deliverNames like '%${deliverNames}%' `
    }
    if(billNo) {
        sql += ` and a.billNo='${billNo}' `
    }
    sql += ' order by a.billNo '

    let cargo = await db.query(sql, {type: QueryTypes.SELECT})

    if (cargo.length > 0) {
        let iid = []
        cargo.map(row => {
            iid.push(row.id)
        })
        let cargoInfoGoods = await db.query(`select * from 
             ps_cargo_info_goods where tenantId=${tenantId} and iid in(${iid.join(',')}  ) order by invName `, {type: QueryTypes.SELECT})
        let gpGoods = []
        let grp = []
        if(cargoInfoGoods.length > 0) {
            let summarized = summarizeItems(cargoInfoGoods)
            grp =  Object.values(summarized);
        }
        for (let i = 0; i < grp.length; i++) {
            if(tool.xe.toNumber(grp[i].calNum) > 0) {
                if(grp[i].unit1 && grp[i].unit2) {
                    let gps = tool.xe.multiply(grp[i].qty,grp[i].calNum)/grp[i].specInt
                    let zhengjian = Math.floor(gps)

                    let lingp = tool.xe.subtract(gps, zhengjian)
                    let ping = tool.xe.toFixed(tool.xe.multiply(lingp, grp[i].specInt), 0)
                    grp[i].assQty = ''
                    if(zhengjian !== 0) {
                        grp[i].assQty = zhengjian + grp[i].unit1
                    }
                    if(ping !== 0) {
                        grp[i].assQty = grp[i].assQty + (ping + grp[i].unit2)
                    }
                }
                else {
                    grp[i].assQty =  grp[i].qty + grp[i].unit
                }
            }
            else {
                grp[i].assQty =  grp[i].qty + grp[i].unit
            }
            gpGoods.push(grp[i])
        }
        if(excel) {
            for (let i = 0; i < gpGoods.length; i++) {
                for (let j = 0; j < cargo.length; j++) {
                    if(gpGoods[i].iid === cargo[j].id) {
                        gpGoods[i].stat = cargo[j].stat
                        gpGoods[i].psBillNo = cargo[j].psBillNo
                        gpGoods[i].psBillDate = cargo[j].psBillDate
                        gpGoods[i].billBillNo = cargo[j].billBillNo
                        gpGoods[i].deliverNames = cargo[j].deliverNames
                    }
                }
            }
            let rets = await tool.doExcelOut(ctx,gpGoods,{fileName:'配送明细'},[
                {field: 'stat', title: '状态',excelOut: true},
                {field: 'psBillNo', title: '配送号',excelOut: true},
                {field: 'psBillDate', title: '配送时间',excelOut: true},
                {field: 'billBillNo', title: '业务票号',excelOut: true},
                {field: 'deliverNames', title: '送货人',excelOut: true},
                {field: 'invName', title: '商品',excelOut: true},
                {field: 'qty', title: '数量',excelOut: true},
                {field: 'unit', title: '单位',excelOut: true},
            ])
            return rets
        }
        else {
            return ctx.suc('', {cargo, goods:gpGoods})
        }
    }
    else {
        return ctx.err('无数据')
    }
})



module.exports = router;